package org.example.top40;

public class main22 {
    //反转链表Ⅱ
    //输入：head = [1,2,3,4,5], left = 2, right = 4 输出：[1,4,3,2,5]
    //需要pre提前放置，cur=pre.next，next
    //for循环里反转，先删next，在将next往前插入
    public static void main(String[] args) {
        ListNode head = builder();
        int left=2;
        int right=4;
        ListNode node=reverseBetween(head,left,right);
        System.out.println(node.next.val);
    }

    private static ListNode reverseBetween(ListNode head, int left, int right) {
        ListNode dummy=new ListNode(-1);
        dummy.next=head;
        ListNode pre=dummy;
        for (int i = 0; i < left - 1; i++) {
            pre=pre.next;
        }
        ListNode cur=pre.next;
        ListNode next;
        for (int i = 0; i < right - left; i++) {
            next=cur.next;
            cur.next=next.next;
            next.next=pre.next;
            pre.next=next;
        }
        return dummy.next;

    }

    private static ListNode builder(){
        ListNode head = new ListNode(1);
        ListNode node1 = new ListNode(2);
        ListNode node2 = new ListNode(3);
        ListNode node3 = new ListNode(4);
        ListNode node4 = new ListNode(5);
        head.next=node1;
        node1.next=node2;
        node2.next=node3;
        node3.next=node4;
        return head;
    }
}
